// Package service
// Created by GoLand
// @User: lenora
// @Date: 2023/12/12
// @Time: 14:44

package service

import (
	"camp/microbook/internal/repository"
	"camp/microbook/internal/service/sms"
	"context"
	"fmt"
	"math/rand"
	"time"
)

const tplId = "449739"

type CodeService interface {
	Send(ctx context.Context, biz, phone string) error
	Verify(ctx context.Context, biz, phone, inputCode string) error
}

type codeService struct {
	repo repository.CodeRepository
	sms  sms.Service
}

func NewCodeService(repo repository.CodeRepository, smsSvc sms.Service) CodeService {
	return &codeService{
		repo: repo,
		sms:  smsSvc,
	}
}

func (svc *codeService) Send(ctx context.Context, biz, phone string) error {
	//redis中是否包含对应key
	//key是否有过期时间
	//过期时间是否大于某个时间节点,判断是否频繁发送
	//以上部分在redis的lua脚本中已做判断
	code := svc.generateCode()
	err := svc.repo.Set(ctx, biz, phone, code)
	if err != nil {
		return err
	}
	//验证码发送
	return svc.sms.Send(ctx, tplId, []string{code}, phone)
}

func (svc *codeService) Verify(ctx context.Context, biz, phone, inputCode string) error {
	return svc.repo.Verify(ctx, biz, phone, inputCode)
}

func (svc *codeService) generateCode() string {
	rand.Seed(time.Now().Unix())
	code := rand.Intn(1000000)
	return fmt.Sprintf("%06d", code)
}
